package com.atguigu.yygh.user.controller;

import com.alibaba.fastjson.JSONObject;

import com.atguigu.yygh.common.exception.HospitalException;
import com.atguigu.yygh.common.helper.JwtHelper;
import com.atguigu.yygh.common.result.Result;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.config.ConstantPropertiesUtil;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.utils.HttpClientUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/user/wx")

public class WeixinApiController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取微信登录参数
     */
    @GetMapping("getLoginParam")
    @ResponseBody
    public Result genQrConnect(HttpSession session) throws UnsupportedEncodingException {
        System.out.println(ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL);
        String redirectUri = URLEncoder.encode(ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL, "UTF-8");
        Map<String, Object> map = new HashMap<>();
        System.out.println("redirectUri"+redirectUri);
        map.put("appid", ConstantPropertiesUtil.WX_OPEN_APP_ID);
        map.put("redirectUri", redirectUri);
        map.put("scope", "snsapi_login");
        map.put("state", System.currentTimeMillis()+"");//System.currentTimeMillis()+""
        return Result.ok(map);
    }

    /**
     * 微信登录回调
     *
     * @param code
     * @param state
     * @return
     */
    @GetMapping("callback")
    public String callback( String code, String state) {
        //获取授权临时票据
        System.out.println("微信授权服务器回调。。。。。。");
        System.out.println("state = " + state);
        System.out.println("code = " + code);

        if (StringUtils.isEmpty(state) || StringUtils.isEmpty(code)) {
//            log.error("非法回调请求");
            throw new HospitalException(ResultCodeEnum.ILLEGAL_CALLBACK_REQUEST_ERROR);
        }

        //使用code和appid以及appscrect换取access_token
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");

        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                code);

        String result = null;
        try {
            result = HttpClientUtils.get(accessTokenUrl);
        } catch (Exception e) {
            throw new HospitalException(ResultCodeEnum.FETCH_ACCESSTOKEN_FAILD);
        }

        System.out.println("使用code换取的access_token结果 = " + result);

        JSONObject resultJson = JSONObject.parseObject(result);
        if(resultJson.getString("errcode") != null){
//            log.error("获取access_token失败：" + resultJson.getString("errcode") + resultJson.getString("errmsg"));
            throw new HospitalException(ResultCodeEnum.FETCH_ACCESSTOKEN_FAILD);
        }

        String accessToken = resultJson.getString("access_token");
        String openId = resultJson.getString("openid");
//        log.info(accessToken);
//        log.info(openId);

        //根据access_token获取微信用户的基本信息
        //先根据openid进行数据库查询
         UserInfo userInfo = userInfoService.getByOpenid(openId);
        // 如果查到用户信息并且有手机号,直接登陆
         if(null != userInfo && StringUtils.isNotEmpty(userInfo.getPhone()) && StringUtils.isNotEmpty(userInfo.getNickName()) ){
             String token = JwtHelper.createToken(userInfo.getId(), userInfo.getName());
             redisTemplate.opsForValue().set(userInfo.getPhone(),token);
             System.out.println("aaa");
             System.out.println("bbb");
             return "redirect:" + ConstantPropertiesUtil.YYGH_BASE_URL + "/weixin/callback?token="+token+"&openid="+openId+"&name="+URLEncoder.encode(userInfo.getNickName())+"&phone="+userInfo.getPhone();
         }


        // 如果查到用户信息但是没有手机号,跳到手机号登陆页面
        if(null != userInfo && StringUtils.isEmpty(userInfo.getPhone())){


//             String token = JwtHelper.createToken(userInfo.getId(), name);

             return "redirect:" + ConstantPropertiesUtil.YYGH_BASE_URL + "/weixin/callback?token="+""+"&openid="+openId+"&name="+URLEncoder.encode(userInfo.getNickName());
        }


        //没有查到用户信息,直接插入一条记录,然后跳转到手机号页面
        if(null == userInfo){
            //使用access_token换取受保护的资源：微信的个人信息,插入数据库
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openId);
            String resultUserInfo = null;
            try {
                resultUserInfo = HttpClientUtils.get(userInfoUrl);
            } catch (Exception e) {
                throw new HospitalException(ResultCodeEnum.FETCH_USERINFO_ERROR);
            }
            System.out.println("使用access_token获取用户信息的结果 = " + resultUserInfo);

            JSONObject resultUserInfoJson = JSONObject.parseObject(resultUserInfo);
            if(resultUserInfoJson.getString("errcode") != null){
//            log.error("获取用户信息失败：" + resultUserInfoJson.getString("errcode") + resultUserInfoJson.getString("errmsg"));
                throw new HospitalException(ResultCodeEnum.FETCH_USERINFO_ERROR);
            }
            System.out.println(resultUserInfo);
            //解析用户信息
            String nickname = resultUserInfoJson.getString("nickname");
            String headimgurl = resultUserInfoJson.getString("headimgurl");
            UserInfo userInfo1 = new UserInfo();
            userInfo1.setName(nickname);
            userInfo1.setNickName(nickname);
            userInfo1.setOpenid(openId);
            userInfoService.save(userInfo1);
            String name = URLEncoder.encode(userInfo1.getName());
            return "redirect:" + ConstantPropertiesUtil.YYGH_BASE_URL + "/weixin/callback?token="+""+"&openid="+openId+"&name="+name;

        }





        return null;
    }
}